<script setup>
import { ref } from 'vue'
import { addBusinessForMemberService } from '@/api/business.js'
import UserCarSelect from './UserCarSelect.vue'

const visibleDialog = ref(false)

const project = ref()

const BusinessAddDTO = ref({
  projectId: null, // 服务项目id
  carId: null, // 车辆id
  plateNumber: null, // 车牌号
  payMethod: null // 付款方式
})

// 向外暴露方法
const open = (row) => {
  visibleDialog.value = true // 打开弹出框
  project.value = row
  BusinessAddDTO.value.projectId = row.id
}

// 支付方式选择器
const showPayMethodPicker = ref(false)
const payMethodColumns = [
  { text: '余额', value: '余额' },
  { text: '微信', value: '微信' },
  { text: '支付宝', value: '支付宝' },
  { text: '现金', value: '现金' }
]
const handlePayMethodPickerConfirm = ({ selectedOptions }) => {
  showPayMethodPicker.value = false
  BusinessAddDTO.value.payMethod = selectedOptions[0].value
}

// 车辆选择器
const showCarSelectPopup = ref(false)
const handleCarSelectConfirm = (car) => {
  showCarSelectPopup.value = false
  BusinessAddDTO.value.carId = car.id
  BusinessAddDTO.value.plateNumber = car.plateNumber
}

// 确认预约
const emit = defineEmits(['success'])
const handleBook = async () => {
  await addBusinessForMemberService(BusinessAddDTO.value)
  showNotify({
    type: 'success',
    message: '预约成功'
  })
  visibleDialog.value = false
  emit('success')
}

// 完成/取消预约
const handleClose = () => {
  Object.keys(BusinessAddDTO.value).forEach((key) => {
    BusinessAddDTO.value[key] = null
  })
  visibleDialog.value = false
}

defineExpose({
  open
})
</script>

<template>
  <van-dialog
    v-model:show="visibleDialog"
    title="服务项目预约"
    show-cancel-button
    @confirm="handleBook"
    @close="handleClose"
  >
    <van-cell-group inset>
      <van-cell title="服务名称" :value="project.name" />
      <van-cell title="服务价格" :value="`¥${(project.price / 100).toFixed(2)}`" />
      <van-cell
        title="服务车辆"
        is-link
        :value="BusinessAddDTO.plateNumber || '请选择车辆'"
        @click="showCarSelectPopup = true"
      />
      <van-cell
        title="付款方式"
        is-link
        :value="BusinessAddDTO.payMethod || '请选择付款方式'"
        @click="showPayMethodPicker = true"
      />
    </van-cell-group>
  </van-dialog>
  <!-- 支付方式选择器 -->
  <van-popup v-model:show="showPayMethodPicker" destroy-on-close round position="bottom">
    <van-picker
      title="请选择付款方式"
      :columns="payMethodColumns"
      @cancel="showPayMethodPicker = false"
      @confirm="handlePayMethodPickerConfirm"
    />
  </van-popup>
  <!-- 车辆选择器 -->
  <van-popup
    v-model:show="showCarSelectPopup"
    destroy-on-close
    round
    position="bottom"
    :style="{ height: '50%' }"
  >
    <user-car-select @selected="handleCarSelectConfirm"></user-car-select>
  </van-popup>
</template>

<style lang="scss" scoped></style>
